using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using community.Data;
using System.Linq;
using System;

namespace community.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DashboardController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public DashboardController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取统计数据
        /// </summary>
        /// <returns>统计数据</returns>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetStatistics()
        {
            // 居民总数
            var totalResidents = await _context.Residents.CountAsync();

            // 投诉处理情况
            var totalComplaints = await _context.Complaints.CountAsync();
            var processedComplaints = await _context.Complaints
                .CountAsync(c => c.Status == "Processed");

            // 已举办活动总数
            var totalEvents = await _context.CommunityEvents
                .CountAsync(e => e.EndTime < DateTime.UtcNow);

            // 物业费总收入
            var totalPropertyFees = await _context.PropertyFees
                .Where(p => p.IsPaid)
                .SumAsync(p => p.Amount);

            return Ok(new
            {
                TotalResidents = totalResidents,
                Complaints = new
                {
                    Processed = processedComplaints,
                    Total = totalComplaints
                },
                TotalEvents = totalEvents,
                TotalPropertyFees = totalPropertyFees
            });
        }

        /// <summary>
        /// 获取本年度物业费收入图表数据
        /// </summary>
        /// <returns>物业费收入图表数据</returns>
        [HttpGet("property-fee-chart")]
        public async Task<IActionResult> GetPropertyFeeChart()
        {
            var currentYear = DateTime.UtcNow.Year;
            var startDate = new DateTime(currentYear, 1, 1);
            var endDate = new DateTime(currentYear, 12, 31);

            var monthlyFees = await _context.PropertyFees
                .Where(p => p.UpdatedAt >= startDate && p.UpdatedAt <= endDate && p.IsPaid )
                .GroupBy(p => new { p.UpdatedAt.Year, p.UpdatedAt.Month })
                .Select(g => new
                {
                    Month = g.Key.Month,
                    TotalAmount = g.Sum(p => p.Amount)
                })
                .OrderBy(g => g.Month)
                .ToListAsync();

            // 填充缺失的月份数据
            var result = Enumerable.Range(1, 12)
                .Select(month => new
                {
                    Month = month,
                    TotalAmount = monthlyFees.FirstOrDefault(m => m.Month == month)?.TotalAmount ?? 0
                })
                .ToList();

            return Ok(result);
        }
    }
} 